package cn.xo68.boot.ui.controller;

import cn.xo68.boot.ui.common.RequireConfigBuilder;
import cn.xo68.boot.ui.entity.RequirePathMapping;
import cn.xo68.boot.ui.properties.WebUiProperties;
import cn.xo68.core.date.DateTime;
import cn.xo68.core.util.JsonUtil;
import cn.xo68.core.util.StringTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;

import java.util.concurrent.TimeUnit;

@RequestMapping("/ui")
@Controller
public class UiController {

    @Autowired
    private JsonUtil jsonUtil;

    @Autowired
    private WebUiProperties webUiProperties;

    /**
     * require 初始本化配置文件生成接口
     * @param defaultMain
     * @param request
     * @return
     */
    @GetMapping("/require-init.js")
    public ResponseEntity<String> resource(@RequestParam(name = "defaultMain",required = false) String defaultMain, WebRequest request){

        String eTag = webUiProperties.getVersionValue();
        if(WebUiProperties.VERSION_VALUE_NOW.equals(webUiProperties.getVersionValue())){
            eTag=String.valueOf(DateTime.Now().getTime());
        }

        if (request.checkNotModified(eTag)) {
            return null;
        }

        RequireConfigBuilder requireConfigBuilder=RequireConfigBuilder.getInstance();
        if(webUiProperties.getPathMappings().entrySet().size()>0){
            webUiProperties.getPathMappings().entrySet().forEach(entry -> {
                requireConfigBuilder.addPathMapping(new RequirePathMapping(entry.getKey(),entry.getValue()));
            });
        }
        requireConfigBuilder.addPathMapping(new RequirePathMapping("siteConfig",webUiProperties.getSiteConfigPath()));
        requireConfigBuilder.addPathMapping(new RequirePathMapping("restTemplate",webUiProperties.getRestTemplatePath()));


        if(StringTools.isNotEmpty(defaultMain)){
            requireConfigBuilder.addDeps(defaultMain);
        }else {
            requireConfigBuilder.addDeps(webUiProperties.getDefaultMain());
        }

        StringBuilder outSb=new StringBuilder();

        outSb.append(";(function () {\r\n");
        outSb.append("let cfg="+jsonUtil.toString(requireConfigBuilder.build(),true)+"\r\n");

        outSb.append("cfg.baseUrl=wxContext.getBaseUrl();\r\n");

        if(WebUiProperties.VERSION_VALUE_NOW.equals(webUiProperties.getVersionValue())){
            outSb.append("cfg.urlArgs='"+webUiProperties.getVersionKey()+"='+"+webUiProperties.getVersionValue()+"\r\n");
        }else {
            outSb.append("cfg.urlArgs='"+webUiProperties.getVersionKey()+"="+webUiProperties.getVersionValue()+"'"+"\r\n");
        }
        outSb.append("require.config(cfg);"+"\r\n");
        outSb.append("})()"+"\r\n");

        CacheControl cacheControl = CacheControl.maxAge(webUiProperties.getScriptCacheHours(), TimeUnit.HOURS);
        if(webUiProperties.getScriptCacheHours()<=0){
            cacheControl=CacheControl.noCache();
        }

        //response.s
        return ResponseEntity.status(HttpStatus.OK)
                .contentType(MediaType.parseMediaType("application/javascript;charset=UTF-8"))
                .eTag(eTag)
                .cacheControl(cacheControl)
                .body(outSb.toString());
    }
}
